package com.kakame.codenews.base.util;

import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;

public class ImageUtil {

	public FileInputStream input = null;
	public FileOutputStream output = null;
	// 输出图片地址
	public String out = null;

	public void cutImage(String type, int x, int y, int width, int height) throws IOException {

		ImageInputStream imageStream = null;
		try {
			String imageType = (null == type || "".equals(type)) ? "jpg" : type;
			Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(imageType);
			ImageReader reader = readers.next();
			imageStream = ImageIO.createImageInputStream(input);
			reader.setInput(imageStream, true);
			ImageReadParam param = reader.getDefaultReadParam();
			Rectangle rect = new Rectangle(x, y, width, height);
			param.setSourceRegion(rect);
			BufferedImage bi = reader.read(0, param);
			ImageIO.write(bi, imageType, new File(out));
			/* ImageIO.write(bi, imageType, output); */
			/*
			 * 假如输出到原图片地址，ImageIO.write(),,第三个参数必须 new File 而不是一个 FileOutputStream对象 ，否则报错
			 */
		} finally {
			if (input != null)
				input.close();
			if (imageStream != null)
				imageStream.close();

		}
	}
}